package com.situ.day19;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;

public class DBDemo {

	@Test
	public void test1() {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		String sql1 = "UPDATE account SET money=money-1000 WHERE name='张三';";
		String sql2 = "UPDATE account SET money=money+1000 WHERE name1='李四';";
		try {
			connection = JDBCUtil.getConnection();
			//autoCommit - 为 true 表示启用自动提交模式；
			//为 false 表示禁用自动提交模式（默认情况下就是true）
			connection.setAutoCommit(false);
			preparedStatement = connection.prepareStatement(sql1);
			preparedStatement.executeUpdate();
			System.out.println(preparedStatement);
			int i = 3 / 0;
			preparedStatement = connection.prepareStatement(sql2);
			preparedStatement.executeUpdate();
			System.out.println(preparedStatement);
			//减钱和加钱这两个操作都完成之后，才去提交事务
			connection.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				connection.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
	}
	
	@Test
	public void testCallableStatement() {
		Connection connection = null;
		CallableStatement callableStatement = null;
		ResultSet resultSet = null;
		try {
			connection = JDBCUtil.getConnection();
			//sql后面不要加分号：FUNCTION show_student; does not exist
			callableStatement = connection.prepareCall("CALL show_student");
			resultSet = callableStatement.executeQuery();
			while (resultSet.next()) {
				int goodsId = (int) resultSet.getObject("goods_id");
				String goodsName = resultSet.getString("goods_name");
				int goodsNumber = resultSet.getInt("goods_number");
				System.out.println(goodsId + "\t" + goodsName + "\t" + goodsNumber);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, callableStatement, resultSet);
		}
	}
	
	
	
	
	
	
}
